﻿using CommunityToolkit.Mvvm.ComponentModel;
using GameView.Models;
using GameView.Services.Comment;
using System.Net.Http;
using System.Net.Http.Json;

namespace GameView.Services
{
    public partial class AuthService : ObservableObject
    {
        private readonly HttpClient _httpClient;

        [ObservableProperty]
        private bool _isLoading;

        public AuthService()
        {
            _httpClient = new HttpClient
            {
                BaseAddress = new Uri(APIHelper.Auth)
            };
        }

        public async Task<ApiResponse<LoginOutDto>> LoginAsync(string username, string password)
        {
            try
            {
                IsLoading = true;

                var response = await _httpClient.PostAsJsonAsync("login", new
                {
                    UserName = username,
                    Password = password
                });
                var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<LoginOutDto>>(StaticValues.JsonOptions);

                if (apiResponse?.StatusCode == 200)
                {
                    StaticValues.Token = apiResponse.Data.Token;
                }

                return apiResponse ?? new ApiResponse<LoginOutDto> { Errors = "Invalid API response" };
            }
            catch (Exception ex)
            {
                return new ApiResponse<LoginOutDto> { Errors = $"网络错误: {ex.Message}" };
            }
            finally
            {
                IsLoading = false;
            }
        }
    }
}